package com.lib.framework.helper

import android.content.Context
import android.util.Log
import com.lib.framework.manager.ContextManager
import com.lib.framework.utils.FileUtil
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*

/**
 * 保存日志到文件 辅助类
 *
 * @author keanbin
 * @date 2019/2/19
 */
class FileLogHelper(context: Context, logFileName: String?) {

    companion object {

        private val TAG = FileLogHelper::class.java.canonicalName

        // 默认的日志文件名前缀
        private const val DEFAULT_LOG_FILE_NAME_PRE = "log-"

        // 日志文件路径
        var sFileLogPath = ""

        /**
         * 调试开关
         */
        var sDebug = false

        /**
         * 写日志到文件中
         *
         * @param logText 日志文本
         */
        fun writeLog(logText: String): Boolean {
            return FileLogHelper(ContextManager.applicationContext).writeLog(logText)
        }
    }

    private val mContext = context
    private var mLogFileName = logFileName ?: ""

    constructor(context: Context) : this(context, null)

    init {
        if (mLogFileName.isEmpty()) {
            val formatter = SimpleDateFormat("yyyy-MM-dd")
            val date = formatter.format(Date())
            mLogFileName = "$DEFAULT_LOG_FILE_NAME_PRE$date.text"
        }
    }

    /**
     * 写日志到文件中
     *
     * @param logText 日志文本
     */
    fun writeLog(logText: String): Boolean {
        if (!sDebug) {
            return false
        }

        val sb = StringBuffer()
        val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val time = formatter.format(Date())
        sb.append(time + "\n")
        sb.append(logText + "\n")
        try {
            if (sFileLogPath.isEmpty()) {
                val dir = FileUtil.getCacheDirByType(mContext, "log") ?: return false
                sFileLogPath = dir.absolutePath + "/"
            }

            val dir = File(sFileLogPath)
            if (!dir.exists()) {
                dir.mkdirs()
            }

            if (!dir.exists()) {
                return false
            }

            val fileName = "$sFileLogPath$mLogFileName"
            val fos = FileOutputStream(fileName, true)
            fos.write(sb.toString().toByteArray())
            fos.close()
            return true
        } catch (e: Exception) {
            Log.e(TAG, "an error occured while writing log file...", e)
        }

        return false
    }
}